import functools
import json
import time
import redis
from redis import Redis

mconn = Redis(host="192.168.35.110", port=6379, db=0, decode_responses=True)

LAST_CHECKED = 0.0
IS_UNDER_MAINTENANCE = False


def is_under_maintenance(conn):
    global LAST_CHECKED, IS_UNDER_MAINTENANCE
    if LAST_CHECKED < time.time() - 1:
        LAST_CHECKED = time.time()
        IS_UNDER_MAINTENANCE = bool(conn.get('is_under_maintenance'))
    return IS_UNDER_MAINTENANCE


def set_config(conn, type, component, config):
    conn.set('config:%s:%s' % (type, component), json.dumps(config))


CONFIGS = {}
CHECKED = {}


def get_config(conn, type, component, wait=1):
    key = 'config:%s:%s' % (type, component)
    if CHECKED.get(key) is None:
        CHECKED.setdefault(key, 0)
    if CHECKED.get(key) < time.time() - wait:
        CHECKED[key] = time.time()
        config = json.loads(conn.get(key) or '{}')
        old_config = CONFIGS.get(key)
        if config != old_config:
            CONFIGS[key] = config
    return CONFIGS.get(key)


REDIS_CONNECTIONS = {}


def redis_connection(component, wait=1):
    key = 'config:redis:' + component

    def wrapper(function):
        @functools.wraps(function)
        def call(*args, **kwargs):
            old_config = CONFIGS.get(key, object())
            _config = get_config(mconn, 'redis', component, wait)
            config = {}
            for k, v in _config.items():
               config[k] = v
            if config != old_config:
                REDIS_CONNECTIONS[key] = redis.Redis(**config)
            return function(REDIS_CONNECTIONS.get(key), *args, **kwargs)

        return call

    return wrapper


@redis_connection('logs')
def log_recent(conn,app,message):
    'the old log_recent() code'
    print(message)


def print_hi(name):
    # 在下面的代码行中使用断点来调试脚本。
    print(f'Hi, {name}')  # 按 Ctrl+F8 切换断点。


# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    mconn.set('config:redis:logs',json.dumps({'host':'192.168.35.110','port':6379,'db':0,'decode_responses':True}))
    print(is_under_maintenance(mconn))
    set_config(mconn, 1, 'demo', {"is_under_maintenance": True})
    print(get_config(mconn, 1, 'demo'))
    log_recent('main','user 123 logged in')
    print_hi('PyCharm')

# 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助
